package com.hzw.video

import android.Manifest
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.TimeUtils
import com.hzw.video.decoder.AudioDecoder
import com.hzw.video.decoder.VideoDecoder
import com.hzw.video.muxer.MP4Repack
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {
    companion object {
        const val TAG = "MainActivity"
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (!PermissionUtils.isGranted(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ), 1
            )
        }
//        initPlayer()

        val audioPath = getExternalFilesDir("video")?.absolutePath + "/lol.mp4"
        val videoPath = getExternalFilesDir("video")?.absolutePath + "/jl.mp4"
        val fileName = "video_${
            TimeUtils.millis2String(
                System.currentTimeMillis(),
                TimeUtils.getSafeDateFormat("yyyyMMdd_HHmmss")
            )
        }.mp4"
        val muxerPath = "${getExternalFilesDir("video")?.absolutePath}/$fileName"

        MP4Repack(audioPath, videoPath, muxerPath).start()
    }

    private fun initPlayer() {
//        val path = getExternalFilesDir("video")?.absolutePath + "/lol.mp4"
//        val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/jl.mp4"
        val path = Environment.getExternalStorageDirectory().absolutePath + "/lol.mp4"
        Log.i(TAG, "path = $path")
        val threadPool = Executors.newFixedThreadPool(2)

        val videoDecoder = VideoDecoder(path, surfaceView, null)
        threadPool.execute(videoDecoder)

        val audioDecoder = AudioDecoder(path)
        threadPool.execute(audioDecoder)

        videoDecoder.goOn()
        audioDecoder.goOn()
    }
}